package com.mc.web;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.mc.model.Path;
import com.mc.model.data_download;
import com.mc.service.IDataService;
import com.mc.utils.FileUtil;
import com.mc.utils.PathUtil;
import com.mc.utils.StringUtil2;

@Controller
@RequestMapping("/backend")
public class FileAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(FileAction.class);

	private Path path = null;
	@Autowired private IDataService dataService;
	@RequestMapping("/uploadui")
	public String uploadui(ModelMap modelMap)
	{
		path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:uploadFile","ViewTitle:上传文件","smenu:file","mmenu:upload"});				
		return PathUtil.returnStr(path, modelMap);
	}
	
	@RequestMapping("/uploadfile")
	public String uploadFile(@RequestParam(value = "files", 
	 required = false) MultipartFile [] files,ModelMap modelMap,
	 @RequestParam("dataName")String dataName)
	 {
		 String filepath = FileUtil.getInstance().uploadFiels(files);
		 data_download record = new data_download();
		 record.setDataName(dataName);
		 record.setDataPath(filepath);
		  int reflect_row = dataService.insert(record );
		 if(reflect_row==1)
			{
			modelMap.addAttribute("success", true);
			}else if(reflect_row==0){
				modelMap.addAttribute("success", false);
			}
		 return "forward:/backend/ZiliaoManeger/1";
	 }
	
	@RequestMapping("/ZiliaoManeger/{pageNum}")
	 public String ZiliaoManeger(@PathVariable("pageNum") int num,ModelMap modelMap){
		 int perPage = 8;// 每页显示新闻条数
			//ModelAndView mav = new ModelAndView();
			int rowCount = dataService.selectAllCount();
			int pagecount = rowCount % perPage;
			if (pagecount == 0)// 偶数条记录
				modelMap.addAttribute("pageCount", rowCount / perPage);
			else
				// 奇数条记录
				modelMap.addAttribute("pageCount", rowCount / perPage + 1);
			List<data_download> nab = dataService.selectAllLimit((num-1)*perPage, perPage);
			modelMap.addAttribute("pageNow", num);
			modelMap.addAttribute("allnews", nab);
			path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:downloadData","ViewTitle:文件管理","smenu:file","mmenu:filemag"});
			return PathUtil.returnStr(path, modelMap);
			//	return mav;
	 }
	
	@RequestMapping("/delFile")
	@ResponseBody
	 public String delFile(@RequestParam("id") int id,ModelMap modelMap)
	 {
		logger.info(id);
		 int resultCode = dataService.deleteByPrimaryKey(id);
		// System.out.println(resultCode);
		 if(resultCode!=0)
		 {
			// modelMap.addAttribute("delFile", true);	 
			 return "success";
		 }else{
			 //modelMap.addAttribute("delFile", false);
			 return "fail";
		 }
		 
		// return "forward:/backend/ZiliaoManeger/1";
	 }
	
	@RequestMapping("/download")  
    public void downloadFile(@RequestParam("filename")String filename,HttpServletResponse response){  
        response.setCharacterEncoding("utf-8"); 
        System.out.println(filename);
        response.setContentType("multipart/form-data"); 
        String urlHeader = StringUtil2.getInstance().getPhysicsPath("/ziliao");
        String realFileName =urlHeader+File.separator+ filename ;
        response.setHeader("Content-Disposition", "attachment;fileName="+filename);  
        try {  
            File file=new File(realFileName);  
             
            InputStream inputStream=new FileInputStream(file);  
            OutputStream os=response.getOutputStream();  
            byte[] b=new byte[1024];  
            int length;  
            while((length=inputStream.read(b))>0){  
                os.write(b,0,length);  
            }  
            inputStream.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    } 
}
